// pages/Shophomepage/index.js
import Toast from 'tdesign-miniprogram/toast/index';
const $api = require('../../../utils/request').Api;
const app = getApp()
const login = wx.getStorageSync('login') // login.data.data.memberNumber
 
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: app.globalData.baseImgUrl,
    num: 0,
    numlist: 0,
    list: [],
    vin: '',
    //购物车x坐标
    animationx: 0,
    //购物车y坐标
    animationy: 0,
    //是否显示飞行物，默认不显示
    showdot: false,
    //动画对象
    ani: {},
    //商品记数
    count: 0,
    isCheck: true,
    banner: 'http://111.203.231.105:801/image/shoyebeijing.png',
    title: '',
    announcement: '',
    xiaolanxong: false,
    profilePhoto: '',
    donghuagowuche: '',
    gowuxiaosho: '',
    animationDelay: 0.55,
    ballDisplay: false, //控制球体显示
    ballTop: 100, //球体的top值
    ballLeft: 0, //球体的left值
    shopCartTop: 0,
    shopCartLeft: 0,
    ballToTop: 0,
    ballToLeft: 0,
    originTop: 0, //保留原位置top，其实可以简化掉，暂时不操作，小伙伴看着来
    originLeft: 0, //保留原位置left
    start: false, //控制点击购物的频率
    cartScale: false, //控制点击购物车的放大效果
    listdata: []
 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    // console.log(options == '' ? '' : options.scene);
    // console.log(typeof options.scene);
    // console.log(options.scene);
    let vin = wx.getStorageSync('vin');
    if (vin === '') {
      wx.setStorageSync('vin', options.scene);
    } else {
    }

    // console.log(opt);
    if (Object.keys(options).length === 0) {
      let vin = wx.getStorageSync('vin');
      $api
        .goodsList({
          page: 1,
          size: 20,
          vin: vin||'1234567890',
        })
        .then((res) => {
          // vin: options.scene == '' ? '123456' : options.scene
          console.log(res);
          this.setData({
            list: res.data.data.goodsList,
            vin: vin||'1234567890',
            isCheck: false,
            banner: res.data.data.decorateImage,
            title: res.data.data.title,
            announcement: res.data.data.announcement,
            profilePhoto: res.data.data.profilePhoto,
          });
        });
    } else {
      let i = options == '' ? '' : options.scene.split('"');
      // console.log(i[1]);
      let opt = parseInt(i[1]);
      // wx.setStorageSync('vin', options.scene)
      $api
        .goodsList({
          page: 1,
          size: 20,
          vin: options.scene,
        })
        .then((res) => {
          // vin: options.scene == '' ? '123456' : options.scene
          console.log(res);
          this.setData({
            list: res.data.data.goodsList,
            vin: opt,
            isCheck: false,
            banner: res.data.data.decorateImage,
            title: res.data.data.title,
            announcement: res.data.data.announcement,
            profilePhoto: res.data.data.profilePhoto,
          });
        });
    }
    this.gowuchelista();
    this.getAllVoucher();
  },
  gowuchelista() {
    let login = wx.getStorageSync('login');
    let vin = wx.getStorageSync('vin');
    console.log(login);
    if (login !== '' && login.data !== '' && login.data.code !== 500) {
      $api
        .shoppingCartList({
          memberNumber: login.data.data.memberNumber,
          page: 1,
          size: 10000,
          source: '2',
          vin: vin || '1234567890',
        })
        .then((res) => {
          console.log(res);
          // console.log(res.data);
          // let isEmpty = true;
          this.setData({
            numlist: res.data.data.goodsTotal,
          });
        });
    } else {
      // Toast({
      // 	context: this,
      // 	selector: '#t-toast',
      // 	message: '请先登录，在选购商品！',
      // });
    }
  },

  getAllVoucher () {
    $api.getAllVoucher({
      identifying: '1',
      memberNumber: login.data.data.memberNumber,
      status: '1'
    }).then(({ data: res }) => {
      this.setData({ listdata: res.data.list })
    })
  },
  /**
   * 领取优惠券
   */
  addUserVoucher (e) {
    const { item } = e.currentTarget.dataset
    $api.addUserVoucher({ memberNumber: login.data.data.memberNumber, voucherId: item.id }).then(({ data: res }) => {
      if (res.code !== 200) {
        return wx.showToast({ icon: 'error', title: res.msg, mask: true })
      }
      wx.showToast({ icon: 'success', title: res.msg, mask: true })
      this.getAllVoucher()
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // var that = this
    // //页面渲染完后获取购物车在页面中的坐标
    // const query = wx.createSelectorQuery()
    // query.select('#gowuche').boundingClientRect()
    // query.selectViewport().scrollOffset()
    // query.exec(function (res) {
    // 	let point = res[0]
    // 	//坐标修正，让飞行物可以正好落在购物车正中心，20是飞行物宽度一半然后转化成px
    // 	var xtemp = (point.left + point.right) / 2 - 20 / 750 * wx.getSystemInfoSync().windowWidth
    // 	var ytemp = (point.top + point.bottom) / 2 - 20 / 750 * wx.getSystemInfoSync().windowWidth
    // 	console.log('xtemp : ' + xtemp + ' ytemp : ' + ytemp)
    // 	that.setData({
    // 		//获取修正后坐标
    // 		animationx: xtemp,
    // 		animationy: ytemp
    // 	})
    // })
  },
  addshopcar(e) {
    var that = this;
    if (that.data.showdot == true) {
      return;
    }
    //获取点击点坐标
    var touches = e.touches[0];
    //坐标修正，同上，这么做是为了让飞行点落到点击的中心
    let toptemp = touches.clientY - (20 / 750) * wx.getSystemInfoSync().windowWidth;
    let lefttemp = touches.clientX - (20 / 750) * wx.getSystemInfoSync().windowWidth;
    console.log('toptemp : ' + toptemp + ' lefttemp : ' + lefttemp);
    var animation1 = wx.createAnimation({
      duration: 1,
      timingFunction: 'ease',
    });
    //通过极短的时间让飞行点移动到手指点击位置，同时让飞行点显示出来
    animation1.left(lefttemp).top(toptemp).step();
    that.setData({
      ani: animation1.export(),
      showdot: true,
    });

    //然后让飞行点飞行到购物车坐标处，形成添加效果
    setTimeout(function () {
      const animation = wx.createAnimation({
        duration: 1500,
        timingFunction: 'ease',
      });
      //通过Animation的left和top这两个API，将飞行点移动到购物车坐标处
      animation.left(that.data.animationx).top(that.data.animationy).step();
      that.setData({
        ani: animation.export(),
      });
      setTimeout(
        function () {
          var counttemp = that.data.count + 1;
          that.setData({
            showdot: false,
            ani: null,
            count: counttemp,
          });
        }.bind(this),
        1520,
      ); //这里也是要稍微延后，后隐藏飞行点，然后清除动画，增加购物计数器
    }, 15); //注意这里要稍微延后，保证前面移动到手指点击处的动画完成
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
	//获取购物车位置
    var query = wx.createSelectorQuery();
    query
      .select('.xiandengtashuo')
      .boundingClientRect((rect) => {
        let w = rect.width / 2;
        let h = rect.height / 2;
        this.setData({
          shopCartLeft: rect.left + w,
          shopCartTop: rect.top + h,
        });
      })
      .exec(); // exec 真重要，光调用上面的方法，不调用 exec 是不执行的，自己走过的坑，记录一下子

    console.log('sssssssssss');

    let vin = wx.getStorageSync('vin');
    if (vin === '') {
    } else {
      $api
        .goodsList({
          page: 1,
          size: 20,
          vin: vin,
        })
        .then((res) => {
          // vin: options.scene == '' ? '123456' : options.scene
          console.log(res);
          this.setData({
            list: res.data.data.goodsList,
            vin: vin||'1234567890',
            isCheck: false,
            banner: res.data.data.decorateImage,
            title: res.data.data.title,
            announcement: res.data.data.announcement,
            profilePhoto: res.data.data.profilePhoto,
          });
        });
    }
    this.gowuchelista();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '加载中...',
      theme: 'loading',
      direction: 'column',
    });
    let vin = wx.getStorageSync('vin');
    $api
      .goodsList({
        page: 1,
        size: 20,
        vin: vin,
      })
      .then((res) => {
        // vin: options.scene == '' ? '123456' : options.scene
        console.log(res);
        this.setData({
          list: res.data.data.goodsList,
          isCheck: false,
          banner: res.data.data.decorateImage,
          title: res.data.data.title,
          announcement: res.data.data.announcement,
          profilePhoto: res.data.data.profilePhoto,
        });
        Toast({
          context: this,
          selector: '#t-toast',
          message: '更新数据完成！',
          theme: 'success',
          direction: 'column',
        });
        this.gowuchelista();
        wx.stopPullDownRefresh();
      });
    // }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // },

  scan: function (e) {
    console.log(e);
    let that = this;
    // //app.showError("功能开发中，敬请期待！");

    wx.scanCode({
      success: (res) => {
        // console.log(res.path.split('?')[1]);
        let add = res.path.split('?')[1];
        let arr = add[1];
        console.log(arr);
        //https://dl.lxcx365.com/index.php?m=Goods&a=g_list&m_id=1&mas_id=10&b_id=1&sort=1&type=breakfast

        // if (that.getUrlParam(res.result, "type") == "breakfast") {
        // 	var mId = that.getUrlParam(res.result, "m_id"),
        // 		masId = that.getUrlParam(res.result, "mas_id"),
        // 		bId = that.getUrlParam(res.result, "b_id"),
        // 		sort = that.getUrlParam(res.result, "sort");

        // if(that.data.isOrder){
        //     //有预约订单
        //     wx.navigateTo({
        //         url: '../breakfast/orderList?sort=' + sort + '&isBreakfirst=' + that.data.isBreakfirst,
        //     });
        // }else{
        //     //无预约订单
        //     if(!that.data.isBreakfirst || that.data.Breakfirst.button_sx == 2){
        //         // 未开启现场点餐
        //         app.showError("您还没有预约订单");
        //     }
        //     if(that.data.isBreakfirst && that.data.Breakfirst.button_sx == 1){
        // 已开启现场点餐
        wx.navigateTo({
          url: '/packageA/pages/Shophomepage/index?' + res.path.split('?')[1],
        });
        //     }
        // }

        // } else {
        // 	// res.result = "https://more.octopus.cn/now/order?a=58&p=35&td_channelid=31&uuid=36a15004525b550a16b410060b43e5f&va=1560163672";
        // 	//存入本地存储
        // 	wx.setStorage({
        // 		key: 'zyOder',
        // 		data: res.result
        // 	});

        // 	wx.navigateTo({
        // 		url: '../OutZy/out',
        // 	});
        // }
      },
    });
    // wx.navigateTo({
    //     // url: '../breakfast/index',
    //     // url: '../breakfast/appointment',
    //     // url: '../breakfast/orderList',
    //     url: '../breakfast/index?m_id=1&mas_id=10&b_id=1&sort=2',
    //     // url: '../groupWeek/index',
    //     // url: '../group/index',
    // });
  },
  tiaozhuanxiangqing(e) {
    console.log(e);
    let arr = JSON.stringify(e.currentTarget.dataset.alphaBeta);
    wx.navigateTo({
      url: `/packageA/pages/Shopproductdetails/index?id=${e.currentTarget.dataset.alphaBeta.productNumber}&vin=${e.currentTarget.dataset.alphaBeta.vin}&shippingSpace=${e.currentTarget.dataset.alphaBeta.shippingSpace}`,
    });
  },
  lijiqianggo(e) {
    console.log(e);
    // let list = JSON.stringify(e.currentTarget.dataset.alphaBeta)
    // let data = e.currentTarget.dataset.alphaBeta
    // let add = new Array
    // let arr = add.push(e.currentTarget.dataset.alphaBeta)
    // console.log(data);
    if (e.currentTarget.dataset.alphaBeta.inventory > 0) {
      let list = [
        {
          activityStatus: e.currentTarget.dataset.alphaBeta.activityStatus,
          discount: e.currentTarget.dataset.alphaBeta.discount,
          imgUrl: e.currentTarget.dataset.alphaBeta.imgUrl,
          page: e.currentTarget.dataset.alphaBeta.page,
          price:
            e.currentTarget.dataset.alphaBeta.price === undefined
              ? e.currentTarget.dataset.alphaBeta.yprice
              : e.currentTarget.dataset.alphaBeta.price,
          productId: e.currentTarget.dataset.alphaBeta.productId,
          productNumber: e.currentTarget.dataset.alphaBeta.productNumber,
          productTitle: e.currentTarget.dataset.alphaBeta.productTitle,
          size: e.currentTarget.dataset.alphaBeta.size,
          yprice: e.currentTarget.dataset.alphaBeta.yprice,
          goodsId: e.currentTarget.dataset.alphaBeta.productId,
          conId: e.currentTarget.dataset.alphaBeta.conId,
          shippingSpace: e.currentTarget.dataset.alphaBeta.shippingSpace,
          inventory: e.currentTarget.dataset.alphaBeta.inventory,
        },
      ];
      // console.log(list);
      // console.log(e.currentTarget.dataset.alphaBeta.price === undefined ?
      // 	e.currentTarget.dataset.alphaBeta.yprice : e.currentTarget.dataset.alphaBeta.price);
      let login = wx.getStorageSync('login');
      if (login != '' && login.data.code != 500) {
        let listdata = JSON.stringify(list);
        // let arr = JSON.stringify(e.currentTarget.dataset.alphaBeta)
        // console.log(listdata);
        wx.navigateTo({
          url: `/packageA/pages/Shopbuying/index?data=${listdata}&vin=${e.currentTarget.dataset.alphaBeta.vin}`,
        });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请先绑定手机号',
          duration: 2000,
          icon: 'close-circle',
        });
      }
    } else {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '当前商品已售罄'+'\n'+'请选择其他商品',
      });
    }
  },
  shoptrolley(e) {
    wx.navigateTo({
      url: `/packageA/pages/shoppingtrolley/index?id=${e}`,
    });
  },
  ballAnimation(e) {
//设置显示和起始位置
    // console.log(e);
    var ballTop = e.touches[0].clientY;
    var ballLeft = e.touches[0].clientX;
    this.setData({
      ballTop: ballTop,
      ballLeft: ballLeft,
      ballToTop: this.data.shopCartTop - ballTop,
      ballToLeft: this.data.shopCartLeft - ballLeft,
      ballDisplay: true,
    });
    //延时关闭显示 延时时间和动画持续时间有关
    setTimeout(() => {
      this.setData({
        ballDisplay: false,
      });
    }, this.data.animationDelay * 1000);
  },
  numtianjian(e) {


    if (e.currentTarget.dataset.alphaBeta.inventory > 0) {
      let login = wx.getStorageSync('login');
      if (login != '' && login.data.code != 500) {
        console.log(e);
        let { alphaBeta } = e.currentTarget.dataset;
        console.log(typeof alphaBeta.productId);
        let shuzi = parseInt(alphaBeta.productId);
        let login = wx.getStorageSync('login');
        // const add = []
        // const list = {
        // 	"attr_group_name": "颜色分类",
        // 	"attr_group_id": "144",
        // 	"attr_name": "黑色",
        // 	"attr_id": "185"
        // }
        // add.push(list)
        // console.log(JSON.stringify(add));
        $api
          .getGoodsSku({
            id: shuzi,
          })
          .then((res) => {
            console.log(res.data.data.attr_group_list);
            let listdata = [
              {
                attr_group_name: res.data.data.attr_group_list[0].attr_group_name,
                attr_group_id: res.data.data.attr_group_list[0].attr_group_id,
                attr_name: res.data.data.attr_group_list[0].attr_list[0].attr_name,
                attr_id: res.data.data.attr_group_list[0].attr_list[0].attr_id,
              },
            ];
            wx.request({
              url: app.globalData.baseApiUrl + '/api/shopping/addShoppingCart',
              method: 'POST',
              data: {
                goodsId: alphaBeta.productId,
                // price: alphaBeta.price,
                productSize: JSON.stringify(listdata),
                sizeId: 1,
                sizeName: 1,
                memberNumber: login.data.data.memberNumber,
                source: 2,
                // yuanPrice: alphaBeta.yprice,
                goodsNum: 1,
                vin: alphaBeta.vin,
                shippingSpace: e.currentTarget.dataset.alphaBeta.shippingSpace,
                productNumber: e.currentTarget.dataset.alphaBeta.productNumber,
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
              },
              success: (res) => {
                console.log(res.data);
                if (res.data.code === 1) {

                  this.ballAnimation(e);
                  // const numj = this.data.numlist + 1
                  // this.setData({
                  // 	numlist: numj
                  // })
                  this.setData({
                    donghuagowuche: 'donghuagowuche',
                    gowuxiaosho: 'gowuxiaosho',
                    numlist: 0,
                  });
                  // this.addshopcar(e)
                  setTimeout(() => {
                    this.setData({
                      donghuagowuche: '',
                      gowuxiaosho: '',
                    });
                    this.gowuchelista();
                  }, 1000);
                } else {
                  // wx.showToast({
                  // 	title: res.data.,
                  // 	icon: 'error',
                  // 	duration: 2000
                  // })
                  // console.log(alphaBeta.productTitle);
                  Toast({
                    context: this,
                    selector: '#t-toast',
                    message: alphaBeta.productTitle + ' ' + res.data.msg,
                    duration: 3000,
                  });
                }
              },
              fail: (err) => {
                console.log(err);
              },
              complete: (res) => {
                console.log(res);
              },
            });
          });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请先绑定手机号',
          duration: 2000,
          icon: 'close-circle',
        });
      }
    } else {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '当前商品已售罄'+'\n'+'请选择其他商品',
      });
    }

    // $api.addShoppingCart({
    // 	goodsId: alphaBeta.productId,
    // 	price: alphaBeta.price,
    // 	productSize: JSON.stringify(add),
    // 	sizeId: 1,
    // 	sizeName: 1,
    // 	useId: login.data.data.memberNumber,
    // 	source: 2,
    // 	yuanPrice: alphaBeta.yprice,
    // 	goodsNum: 1,
    // }).then((res) => {
    // 	console.log(res.data.code);
    // 	if (res.data.code != 200) {
    // 		wx.showToast({
    // 			title: '添加商品失败',
    // 			icon: 'error',
    // 			duration: 2000
    // 		})
    // 	} else {
    // 		const numj = this.data.numlist + 1
    // 		this.setData({
    // 			numlist: numj
    // 		})
    // 	}

    // })
  },
});
